package kr.co.exight.onApp;

import java.util.ArrayList;

import library.ActionClass;
import library.ExPreferenceManager;
import library.JsonParser;
import library.Library;
import library.Variables;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TabWidget;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class ActivityCardMap extends MapActivity{



	private MapView mapView;
	private MapController mapController;



	private Location myLocation;


	private ArrayList<RelativeLayout> arrMarker;

	private ExPreferenceManager p;


	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	// �巡�׽� ��ǥ ����

	Context context;

	private JSONObject jsonResult;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_cardmap);
		context = this;

		p = new ExPreferenceManager(context);

		double longi = getIntent().getDoubleExtra("long", 0.0);
		double lati = getIntent().getDoubleExtra("lati", 0.0);


		//ivMyPin = new ImageView(this);
		//ivMyPin.setBackgroundResource(R.drawable.pin);



		mapView = (MapView) findViewById(R.id.card_mapView);

		//	mapView.setOnTouchListener(mOnTouchListener);
		mapView.setClickable(true);

		mapController = mapView.getController();
		// mapView �� mapController �ʱ�ȭ
		setDataFromJSON();



		mapController.setZoom(18);	

		if(longi != 0.0 && lati != 0.0){
			mapController.setCenter(new GeoPoint((int) (lati * 1E6),
					(int) (longi * 1E6)));
		}else{
			mapController.setCenter(Variables.sinChonPoint);
		}


		//Button btnCurrentLoc = (Button)findViewById(R.id.partnerMap_btnMyLocation);
		/*btnCurrentLoc.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(context, "���� ��ġ�� �缳���մϴ�.", 1000).show();
				if(tempMyLocation != null){
					myLocation = tempMyLocation;
				}else if(myLocation == null) {
					getGPSSignal();
				}

				MapView.LayoutParams mapMarkerParams = new MapView.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, geoPoint,
						MapView.LayoutParams.BOTTOM_CENTER);
				mapView.removeView(ivMyPin);
				mapView.addView(ivMyPin, mapMarkerParams);
			}
		});*/

	}



	public void setDataFromJSON(){
		showDialog(0);
		JsonParser parser = new JsonParser(Variables.CARD_URL, new ActionClass(ActivityCardMap.this) {
			@Override
			public void actionSuccess(Object object) {
				// TODO Auto-generated method stub
				try{
					dismissDialog(0);
				}catch(IllegalArgumentException e){
					e.printStackTrace();
				}

				if(p.getItem(ExPreferenceManager.TAG_ONCARD_FIRST) == ""){
					// dialog 띄우기
					DialogNotice dialog = new DialogNotice(ActivityCardMap.this, true);
					dialog.showDialog();
				}

				jsonResult  = (JSONObject)object;
				ActivityCardList.setJSONData(jsonResult);
				try {
					addShopPin();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			@Override
			public void actionFailed() {
				// TODO Auto-generated method stub
				try{
					dismissDialog(0);
				}catch(IllegalArgumentException e){
					e.printStackTrace();
				}
				super.actionFailed();
			}

		});
		parser.start();


	}

	@Override // 로딩바 안보이게 하기
	protected Dialog onCreateDialog(int id) {
		final Dialog dialog = new Dialog(this, R.style.Theme_Dialog);
		View view = getLayoutInflater().inflate(R.layout.dialog_progress, null);
		dialog.setContentView(view);
		dialog.setOnCancelListener(new OnCancelListener() {

			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		return dialog;

	}



	private void addShopPin() throws JSONException {
		//mapView.getOverlays().clear();
		arrMarker = new ArrayList<RelativeLayout>();
		JSONArray data = jsonResult.getJSONArray("spots");
		for(int i = 0; i < data.length(); i++) {
			final JSONObject posData = data.getJSONObject(i);

			RelativeLayout markerLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.pin_marker, null);
			arrMarker.add(markerLayout);
			final TextView markerText = (TextView)markerLayout.findViewById(R.id.cardMap_tvMarker);

			Library.setFontNanumGothic(markerText);
			Library.setTextViewBold(markerText);

			markerText.setText(posData.getJSONArray("phone").getString(1));


			//Text����
			markerLayout.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					ActivityCardDetail.setJSONData(posData);
					Library.startActivity(ActivityCardMap.this, ActivityCardDetail.class);

				}
			});


			GeoPoint geoPoint = new GeoPoint
					((int) (posData.getJSONObject("position").getDouble("latitude") * 1E6),
							(int) (posData.getJSONObject("position").getDouble("longitude") * 1E6));
			MapView.LayoutParams mapMarkerParams = new MapView.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, geoPoint,
					MapView.LayoutParams.BOTTOM_CENTER);
			//arrMarker.get(i).setVisibility(View.VISIBLE);
			mapView.addView(arrMarker.get(i), mapMarkerParams);

			//	Drawable marker = getResources().getDrawable(R.drawable.cooperateshop_small_pin);

			//mapView.getOverlays().add(new MyOverlay(marker, companyInfo.getGps_lat(), companyInfo.getGps_long(), companyInfo.getCompany_name()));
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	public void getGPSSignal() {
		// GPS �޾ƿ���
		final LocationManager locationManager;
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		String provider = LocationManager.NETWORK_PROVIDER;
		Location location = locationManager.getLastKnownLocation(provider);

		if (location != null) {
			myLocation = new Location(location);
			longitude = myLocation.getLongitude();
			latitude = myLocation.getLatitude();

		}

		// ������ ��� �޾ƿ���.
		locationManager.requestLocationUpdates(provider, 0, 0,
				new LocationListener() {

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			public void onProviderEnabled(String provider) {
			}

			public void onProviderDisabled(String provider) {
			}

			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				myLocation = location;
				// Variables.temploc = location;
				locationManager.removeUpdates(this);
			}
		});
	}

	private void createGpsDisabledAlert(){   
		AlertDialog.Builder builder = new AlertDialog.Builder(this);   
		builder.setMessage("정상적인 서비스 활용을 위해\n환경설정->장소 및 보안->\n'무선 네트워크 사용'을 체크하세요")   
		.setCancelable(false)   
		.setPositiveButton("변경하기",   
				new DialogInterface.OnClickListener(){   
			public void onClick(DialogInterface dialog, int id){   
				Intent gpsOptionsIntent = new Intent(   
						android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);   
				startActivityForResult(gpsOptionsIntent, 0);   

			}   
		});   
		/*builder.setNegativeButton("종료하기",   
				new DialogInterface.OnClickListener(){   
			public void onClick(DialogInterface dialog, int id){   
				dialog.cancel();   
			}   
		});  

		AlertDialog alert = builder.create();   
		alert.show();   
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode == 0){
			final LocationManager locationManager;
			locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

			if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){   
				createGpsDisabledAlert(); 
			}else{
				getGPSSignal();
			}
		}
	} */ 
}



